//
// Created by zhuruyi on 2021/3/12.
//

#include "common_util.h"


void *XML_to_RSI(char *xml_file_name, char *out_file_name, asn_app_consume_bytes_f *cb) {
    char buf[1024];
    size_t size;

    FILE *fpXml;

    fpXml = fopen(xml_file_name, "r");
    size = fread(buf, 1, sizeof(buf), fpXml);
    fprintf(stdout, "size= %zu \n", size);
    fclose(fpXml);
    if (!size) {
        fprintf(stderr, "%s: Empty or broken\n", xml_file_name);
        exit(1);
    }

    struct RoadSideInformation *rsi = 0; /* Note this 0! */
    asn_dec_rval_t rval;

    rval = xer_decode(0, &asn_DEF_MessageFrame, (void **) &rsi,
                      buf, size);

    /* Print the decoded Rectangle type as XML */
    xer_fprint(stdout, &asn_DEF_MessageFrame, rsi);

    if (rval.code == RC_OK) {
        FILE *fpBin;
        fpBin = fopen(out_file_name, "w+");
        /* Decoding succeeded */
        asn_enc_rval_t er = uper_encode(&asn_DEF_MessageFrame, 0, rsi, cb, fpBin);
        fclose(fpBin);

        if (er.encoded == -1) {
            fprintf(stderr, "Failed to encode %s\n", asn_DEF_MessageFrame.name);
        } else {
            fprintf(stderr, "%s encoded in %zd bytes\n", asn_DEF_MessageFrame.name, er.encoded);
        }
    } else {
        return nullptr;
    }
}

void *PER_to_XER(char *per_file_name, char *xml_file_name, asn_app_consume_bytes_f *cb) {
    char buf[1024];
    asn_dec_rval_t rval;
    size_t size;
    struct RoadSideInformation *pRoadSideInformation = 0;
    FILE *fp;

    fp = fopen(per_file_name, "rb");
    if (!fp) {
        perror(per_file_name);
        exit(1);
    }

    /* Read up to the buffer size */
    size = fread(buf, 1, sizeof(buf), fp);
    fclose(fp);
    if (!size) {
        fprintf(stderr, "%s: Empty or broken\n", per_file_name);
        exit(1);
    }

    /* Decode the input buffer as Rectangle type */
    rval = uper_decode(0, &asn_DEF_MessageFrame, (void **) &pRoadSideInformation, buf, size, 0, 0);
    if (rval.code != RC_OK) {
        fprintf(stderr, "%s: Broken Rectangle encoding at byte %ld\n", per_file_name,
                (long) rval.consumed);
        exit(1);
    }
    /* Print the decoded Rectangle type as XML */
    xer_fprint(stdout, &asn_DEF_MessageFrame, pRoadSideInformation);

    asn_enc_rval_t ec;
    FILE *desFile;
    desFile = fopen(xml_file_name, "w+");

    ec = xer_encode(&asn_DEF_MessageFrame, pRoadSideInformation, XER_F_BASIC, cb, desFile);
    if (ec.encoded == -1) {
        fprintf(stderr, "Could not encode MessageFrame (at %s)\n", xml_file_name);
        exit(1);
    } else {
        fprintf(stderr, "Created %s with xer encoded MessageFrame\n", xml_file_name);
    }
    fclose(desFile);
}

